package it.ap.sa.core.utils;

import java.io.InputStream;
import java.io.OutputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;

/**
 * @author Alessandro Paolillo
 */
public class JsonParserUtil {
	
	/**
	 * @author Alessandro Paolillo
	 */
	public static <T> T jsonToObject(String json, Class<T> classe) throws Exception{
		return new ObjectMapper().readValue(json,classe);
	}
	/**
	 * @author Alessandro Paolillo
	 */
	public static <T> T jsonToObject(StringWriter json, Class<T> classe) throws Exception{
		return jsonToObject(json.toString(), classe);
	}
	/**
	 * @author Alessandro Paolillo
	 */
	public static <T> T jsonToObject(InputStream inputStream,Class<T> classe) throws Exception{
		return new ObjectMapper().readValue(inputStream, classe);
	}
	/**
	 * @author Alessandro Paolillo
	 */
	public static <T> T jsonToObject(HttpServletRequest request,Class<T> classe) throws Exception{
		return jsonToObject(request.getInputStream(), classe);
	}
	/**
	 * @author Alessandro Paolillo
	 */
	@SuppressWarnings("unchecked")
	public static Map<String,Object> jsonToMap(String json) throws Exception{
		return jsonToObject(json, HashMap.class);
	}
	/**
	 * @author Alessandro Paolillo
	 */
	@SuppressWarnings("unchecked")
	public static Map<String,Object> jsonToMap(StringWriter json) throws Exception{
		return jsonToObject(json, HashMap.class);
	}
	/**
	 * @author Alessandro Paolillo
	 */
	@SuppressWarnings("unchecked")
	public static Map<String,Object> jsonToMap(InputStream inputStream) throws Exception{
		return jsonToObject(inputStream, HashMap.class);
	}
	/**
	 * @author Alessandro Paolillo
	 */
	@SuppressWarnings("unchecked")
	public static Map<String,Object> jsonToMap(HttpServletRequest request) throws Exception{
		return jsonToObject(request, HashMap.class);
	}
	/**
	 * @author Alessandro Paolillo
	 */
	public static String beanToJson(Object jsonObject) throws Exception{
		ObjectMapper mapper = new ObjectMapper();
		ObjectWriter writer = mapper.writer();
		return writer.writeValueAsString(jsonObject);
	}
	/**
	 * @author Alessandro Paolillo
	 */
	public static void writeJsonInOutputStream(OutputStream outputStream, Object jsonObject) throws Exception{
		ObjectMapper mapper = new ObjectMapper();
		ObjectWriter writer = mapper.writer();
		
		writer.writeValue(outputStream, jsonObject);
		
		outputStream.flush();
		outputStream.close();
	}
	/**
	 * @author Alessandro Paolillo
	 */
	public static void writeJsonInResponse(HttpServletResponse response, Object jsonObject) throws Exception{
		writeJsonInOutputStream(response.getOutputStream(), jsonObject);
	}
}